package com.ynkbny.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ynkbny.domain.*;
import com.ynkbny.domain.mongo.DeviceHistoryDataMon;
import com.ynkbny.domain.mongo.PandData;
import com.ynkbny.domain.pojo.DevicePointVO;
import com.ynkbny.mapper.DeviceMapper;
import com.ynkbny.service.*;
import com.ynkbny.service.outsideinterface.MyClient;
import com.ynkbny.util.MongoUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 老狗Api接口-服务实现类
 *
 * @author : juzipi123
 * @date : 2023-7-18
 */
@Slf4j
@Service
public class LaoGouApiServiceImpl implements LaoGouApiService {

    @Value("${laoGou.host}")
    private String host;

    @Value("${laoGou.queryDeviceByProject}")
    private String queryDeviceByProject;

    @Value("${laoGou.QueryProjectDeviceParamStatus}")
    private String QueryProjectDeviceParamStatus;

    @Value("${laoGou.queryProjectList}")
    private String queryProjectList;

    @Value("${laoGou.queryDeviceParamHistoryData}")
    private String queryDeviceParamHistoryData;

    @Value("${laoGou.queryRegionByProject}")
    private String queryRegionByProject;

    @Resource
    private ProjectService projectService;

    @Resource
    private RegionService regionService;

    @Resource
    private DeviceService deviceService;

    @Resource
    private DeviceAttributeService deviceAttributeService;

    @Resource
    private MongoUtil mongoUtil;

    @Resource
    MyClient client;

    @Resource
    PlanDataService planDataService;

    @Resource
    EnterpriseService enterpriseService;

    @Resource
    private DevicePointService devicePointService;

    @Resource
    private TokenService tokenService;

    /**
     * 查询项目列表，只展示项目的id的一个list
     *
     * @author : juzipi123
     * @return 项目ID 的list
     */
    @Override
    public List<String> queryProjectList2() {
        List<String> strings = projectService.projectLis();
        log.info("查询项目列表的结果：{}",strings);
        return strings;
    }

    /**
     * 查询所有项目列表，维护“项目表”
     *
     * @author : juzipi123
     * @return 结果
     */
    @Override
    public String queryProjectList() {
        //老狗登陆地址
        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        //老狗 查询项目的设备列表 地址
        String reqUrl = host + queryProjectList + "?isAll=true";
        log.info("请求地址：{}",reqUrl);
        JSONObject resultJson = JSONUtil.parseObj(client.queryProjectList(reqUrl, token));
        log.info("请求地址返回值：{}",resultJson);

        //调用接口 返回值是200.0 且 结果中的data 不为空
        if ("200.0".equals(String.valueOf(resultJson.get("code")))
                && ObjectUtil.isNotEmpty(resultJson.get("data"))) {
            JSONArray data = JSONUtil.parseArray(resultJson.get("data"));
            log.info("数组：{}", data);

            //如果数据库表“项目表”不为空，先删除数据，在插入
            if (projectService.count() > 0) {
                log.info("表“项目表”不为空，先删除数据");
                projectService.del();
                log.info("删除完成！");
            }

            //循环插入数据
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObj = data.getJSONObject(i);
                Project project = new Project();
                project.setId(String.valueOf(jsonObj.get("id")));
                project.setName(String.valueOf(jsonObj.get("name")));
                project.setConstructionTime(String.valueOf(jsonObj.get("constructionTime")));
                project.setAcreage(String.valueOf(jsonObj.get("acreage")));
                project.setProvince(String.valueOf(jsonObj.get("province")));
                project.setCity(String.valueOf(jsonObj.get("city")));
                project.setCounty(String.valueOf(jsonObj.get("county")));
                project.setAddress(String.valueOf(jsonObj.get("address")));
                project.setTypeId(String.valueOf(jsonObj.get("typeId")));
                project.setImgUrl(String.valueOf(jsonObj.get("imgUrl")));
                project.setPropertyOwner(String.valueOf(jsonObj.get("propertyOwner")));
                project.setEnergyConsumption(String.valueOf(jsonObj.get("energyConsumption")));
                project.setRemarks(String.valueOf(jsonObj.get("remarks")));
                project.setEnableTime(String.valueOf(jsonObj.get("enableTime")));
                project.setContractor(String.valueOf(jsonObj.get("contractor")));
                project.setPropertyMgmt(String.valueOf(jsonObj.get("propertyMgmt")));
                JSONObject projectType = JSONUtil.parseObj(jsonObj.get("projectType"));
                project.setProjectTypeId(String.valueOf(projectType.get("id")));
                project.setProjectTypeName(String.valueOf(projectType.get("name")));
                project.setState(String.valueOf(jsonObj.get("state")));
                project.setDelFlag(String.valueOf(jsonObj.get("delFlag")));
                log.info("即将新增的新数据：{}",project);
                projectService.save(project);
            }
        }

        //返回调用老狗接口 后的结果
        log.info("返回调用老狗接口 后的结果:{}",resultJson.toString());
        return resultJson.toString();
    }

    /**
     * QueryRegionByProject - 查询所有项目下的区域列表,维护“区域表-region”
     *
     * @author : juzipi123
     * @return 结果
     */
    @Override
    public String queryRegionByProject() {

        //如果数据库表“区域表”不为空，先删除数据，在插入
        if (regionService.count() > 0) {
            log.info("数据库表“区域表”不为空，先删除数据");
            regionService.del();
        }

        for (String projectLi : projectService.projectLis()) {
            String reqUrl = host + queryRegionByProject + "?projId=" + Long.parseLong(projectLi);
            log.info("请求地址：{}",reqUrl);

            //老狗登陆地址
            String token = tokenService.getLaoGouToken();
            log.info("获取老狗登陆token：{}",token);

            String s = client.QueryRegionByProject(reqUrl, token);
            log.info("请求地址返回值：{}",s);
            JSONObject resultJson = JSONUtil.parseObj(s);

            if ("200.0".equals(String.valueOf(resultJson.get("code"))) && ObjectUtil.isNotEmpty(resultJson.get("data"))) {
                JSONArray data = JSONUtil.parseArray(resultJson.get("data"));
                log.info("数组：{}", data);
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObj = data.getJSONObject(i);
                    Region region = new Region();
                    region.setProjId(projectLi);
                    region.setRegionId(jsonObj.getStr("id"));
                    region.setRegionName(jsonObj.getStr("name"));
                    region.setRemarks(jsonObj.getStr("remarks"));
                    log.info("即将新增的数据：{}",region);
                    regionService.save(region);
                }
            }
        }
        return "区域表-region 更新成功!";
    }

    /**
     * 查询项目的设备列表
     *
     * @author : juzipi123
     * @param projId 项目ID
     * @return 结果
     */
    @Override
    public String queryDeviceByProject(Long projId, String username, String password) {
        log.info("传入的参数：{},{},{}",projId,username,password);

        //老狗登陆地址
        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        String reqUrl = host + queryDeviceByProject + "?projId=" + projId;
        JSONObject resultJson = JSONUtil.parseObj(client.queryDeviceByProject(reqUrl, token));

        //判断，如果在表存在此项目的 相关信息，先删除，再插入
        if (deviceService.count() > 0) {
            deviceService.delByProjId(projId);
        }

        //设备ID
        List<Object> deviceList = new ArrayList<>();
        if ("200.0".equals(String.valueOf(resultJson.get("code"))) && ObjectUtil.isNotEmpty(resultJson.get("data"))) {
            JSONArray data = JSONUtil.parseArray(resultJson.get("data"));
            log.info("数组：{}", data);
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObj = data.getJSONObject(i);
                Device device = new Device();
                device.setProjectId(String.valueOf(jsonObj.get("projectId")));
                device.setRegionId(String.valueOf(jsonObj.get("regionId")));
                device.setDeviceId(String.valueOf(jsonObj.get("id")));
                device.setName(String.valueOf(jsonObj.get("name")));
                device.setBrand(String.valueOf(jsonObj.get("brand")));
                device.setModel(String.valueOf(jsonObj.get("model")));
                device.setPower(String.valueOf(jsonObj.get("power")));
                device.setProduceTime(String.valueOf(jsonObj.get("produceTime")));
                device.setTypeId(String.valueOf(jsonObj.get("typeId")));
                JSONObject deviceType = JSONUtil.parseObj(jsonObj.get("deviceType"));
                device.setDeviceTypeId(String.valueOf(deviceType.get("id")));
                device.setDeviceTypeName(String.valueOf(deviceType.get("name")));
                log.info("即将新增的数据：{}",device);
                deviceService.save(device);
            }
        }

        return resultJson.toString();
    }

    /**
     * 查询所有项目的设备列表2,维护“设备表-device”
     *
     * @author : juzipi123
     * @return 结果
     */
    @Override
    public String queryDeviceByProject2() {

        //判断，如果在表存在数，先删除，再插入
        if (deviceService.count() > 0) {
            log.info("设备表-device 存在数据，先删除");
            deviceService.del();
        }
        List<String> projectLis = projectService.projectLis();
        for (String projectLi : projectLis) {
            String reqUrl = host + queryDeviceByProject + "?projId=" + Long.parseLong(projectLi);
            log.info("请求地址：{}",reqUrl);

            //老狗登陆地址
            String token = tokenService.getLaoGouToken();
            log.info("获取老狗登陆token：{}",token);
            JSONObject resultJson = JSONUtil.parseObj(client.queryDeviceByProject(reqUrl, token));
            log.info("请求地址返回值：{}",resultJson);

            if ("200.0".equals(String.valueOf(resultJson.get("code"))) &&
                    ObjectUtil.isNotEmpty(resultJson.get("data"))) {
                JSONArray data = JSONUtil.parseArray(resultJson.get("data"));

                log.info("数组：{}", data);
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObj = data.getJSONObject(i);
                    Device device = new Device();
                    device.setProjectId(String.valueOf(jsonObj.get("projectId")));
                    device.setRegionId(String.valueOf(jsonObj.get("regionId")));
                    device.setDeviceId(String.valueOf(jsonObj.get("id")));
                    device.setName(String.valueOf(jsonObj.get("name")));
                    device.setBrand(String.valueOf(jsonObj.get("brand")));
                    device.setModel(String.valueOf(jsonObj.get("model")));
                    device.setPower(String.valueOf(jsonObj.get("power")));
                    device.setProduceTime(String.valueOf(jsonObj.get("produceTime")));
                    device.setTypeId(String.valueOf(jsonObj.get("typeId")));
                    JSONObject deviceType = JSONUtil.parseObj(jsonObj.get("deviceType"));
                    device.setDeviceTypeId(String.valueOf(deviceType.get("id")));
                    device.setDeviceTypeName(String.valueOf(deviceType.get("name")));
                    Device device1 = deviceService.selectByDeviceId(String.valueOf(jsonObj.get("id")));
                    if(ObjectUtil.isNotEmpty(device1)){
                        deviceService.delByDeviceId(device1.getDeviceId());
                    }
                    log.info("即将新增的数据：{}",device);
                    deviceService.save(device);
                }
            }
        }
        return "设备表 所有项目更新完成";
    }

    /**
     * 查询单个项目设备的属性快照，维护“设备的属性快照-device_attribute”
     *
     * @author : juzipi123
     * @param projId   项目ID
     * @return 结果
     */
    @Override
    public String QueryProjectDeviceParamStatus(Long projId) {
        log.info("入参：{}",projId);

        //老狗登陆地址
        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        String reqUrl = host + QueryProjectDeviceParamStatus + "?projId=" + projId;
        log.info("请求地址：{}",reqUrl);
        JSONObject resultJson = JSONUtil.parseObj(client.QueryProjectDeviceParamStatus(reqUrl, token));

        log.info("请求地址返回值：{}",resultJson);
        if ("200.0".equals(String.valueOf(resultJson.get("code")))
                && ObjectUtil.isNotEmpty(resultJson.get("data"))) {
            JSONArray data = JSONUtil.parseArray(resultJson.get("data"));
            log.info("数组：{}", data);
            if (deviceAttributeService.count() > 0) {
                log.info("数据库存在项目：{}的数据，先删除",projId);
                deviceAttributeService.delByProjId(projId);
                log.info("删除完成！");
            }
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObj = data.getJSONObject(i);
                DeviceAttribute deviceAttribute = new DeviceAttribute();
                deviceAttribute.setProjectId(String.valueOf(jsonObj.get("projectId")));
                deviceAttribute.setRegionId(String.valueOf(jsonObj.get("regionId")));
                deviceAttribute.setDeviceId(String.valueOf(jsonObj.get("deviceId")));

                JSONObject deviceType = JSONUtil.parseObj(jsonObj.get("deviceType"));
                deviceAttribute.setDeviceTypeId(String.valueOf(deviceType.get("id")));
                deviceAttribute.setDeviceTypeName(String.valueOf(deviceType.get("name")));
                deviceAttribute.setWorkload(String.valueOf(jsonObj.get("workload")));
                deviceAttribute.setElec(String.valueOf(jsonObj.get("elec")));
                deviceAttribute.setErrorParamNum(String.valueOf(jsonObj.get("errorParamNum")));
                deviceAttribute.setWarnParamNum(String.valueOf(jsonObj.get("warnParamNum")));
                deviceAttribute.setErrorTimeSum(String.valueOf(jsonObj.get("errorTimeSum")));
                deviceAttribute.setRunTimeSum(String.valueOf(jsonObj.get("runTimeSum")));
                deviceAttribute.setWarnEventSum(String.valueOf(jsonObj.get("warnEventSum")));
                deviceAttribute.setErrorEventSum(String.valueOf(jsonObj.get("errorEventSum")));
                deviceAttribute.setStatus(String.valueOf(jsonObj.get("status")));
                deviceAttribute.setTimestamp(String.valueOf(jsonObj.get("timestamp")));

                JSONArray jsonParams = JSONUtil.parseArray(jsonObj.get("jsonParams"));
                log.info("数组：{}", jsonParams);
                for (int j = 0; j < jsonParams.size(); j++) {
                    JSONObject jsonParam = jsonParams.getJSONObject(j);
                    deviceAttribute.setQs(String.valueOf(jsonParam.get("qs")));
                    deviceAttribute.setRealvalue(String.valueOf(jsonParam.get("realvalue")));
                    deviceAttribute.setFlag(String.valueOf(jsonParam.get("flag")));
                    deviceAttribute.setAttributeId(String.valueOf(jsonParam.get("attributeId")));
                    deviceAttribute.setParamName(String.valueOf(jsonParam.get("paramName")));
                    deviceAttribute.setValue(String.valueOf(jsonParam.get("value")));
                    deviceAttribute.setUnitName(String.valueOf(jsonParam.get("unitName")));
                    deviceAttribute.setDataType(String.valueOf(jsonParam.get("dataType")));
                    log.info("即将新增的数据: {}",deviceAttribute);
                    deviceAttributeService.save(deviceAttribute);
                }
            }
        }
        return resultJson.toString();
    }

    /**
     * 查询所有项目设备的属性快照，维护“设备的属性快照-device_attribute”
     *
     * @author : juzipi123
     * @return 结果
     */
    @Override
    public String QueryProjectDeviceParamStatus2() {

        //老狗登陆地址
        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        if (deviceAttributeService.count() > 0) {
            log.info("设备的属性快照表-device_attribute 存在数据，先删除 ");
            deviceAttributeService.del();
        }
        List<String> list = projectService.projectLis();
        for (String projectLi : list) {
            String reqUrl = host + QueryProjectDeviceParamStatus + "?projId=" + Long.parseLong(projectLi);
            JSONObject resultJson = JSONUtil.parseObj(client.QueryProjectDeviceParamStatus(reqUrl, token));
            //设备ID
            if ("200.0".equals(String.valueOf(resultJson.get("code"))) && ObjectUtil.isNotEmpty(resultJson.get("data"))) {
                JSONArray data = JSONUtil.parseArray(resultJson.get("data"));
                log.info("数组：{}", data);
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObj = data.getJSONObject(i);
                    DeviceAttribute deviceAttribute = new DeviceAttribute();
                    deviceAttribute.setProjectId(String.valueOf(jsonObj.get("projectId")));
                    deviceAttribute.setRegionId(String.valueOf(jsonObj.get("regionId")));
                    deviceAttribute.setDeviceId(String.valueOf(jsonObj.get("deviceId")));

                    JSONObject deviceType = JSONUtil.parseObj(jsonObj.get("deviceType"));
                    deviceAttribute.setDeviceTypeId(String.valueOf(deviceType.get("id")));
                    deviceAttribute.setDeviceTypeName(String.valueOf(deviceType.get("name")));
                    deviceAttribute.setWorkload(String.valueOf(jsonObj.get("workload")));
                    deviceAttribute.setElec(String.valueOf(jsonObj.get("elec")));
                    deviceAttribute.setErrorParamNum(String.valueOf(jsonObj.get("errorParamNum")));
                    deviceAttribute.setWarnParamNum(String.valueOf(jsonObj.get("warnParamNum")));
                    deviceAttribute.setErrorTimeSum(String.valueOf(jsonObj.get("errorTimeSum")));
                    deviceAttribute.setRunTimeSum(String.valueOf(jsonObj.get("runTimeSum")));
                    deviceAttribute.setWarnEventSum(String.valueOf(jsonObj.get("warnEventSum")));
                    deviceAttribute.setErrorEventSum(String.valueOf(jsonObj.get("errorEventSum")));
                    deviceAttribute.setStatus(String.valueOf(jsonObj.get("status")));
                    deviceAttribute.setTimestamp(String.valueOf(jsonObj.get("timestamp")));

                    JSONArray jsonParams = JSONUtil.parseArray(jsonObj.get("jsonParams"));
                    log.info("数组：{}", jsonParams);
                    for (int j = 0; j < jsonParams.size(); j++) {
                        JSONObject jsonParam = jsonParams.getJSONObject(j);
                        deviceAttribute.setQs(String.valueOf(jsonParam.get("qs")));
                        deviceAttribute.setRealvalue(String.valueOf(jsonParam.get("realvalue")));
                        deviceAttribute.setFlag(String.valueOf(jsonParam.get("flag")));
                        deviceAttribute.setAttributeId(String.valueOf(jsonParam.get("attributeId")));
                        deviceAttribute.setParamName(String.valueOf(jsonParam.get("paramName")));
                        deviceAttribute.setValue(String.valueOf(jsonParam.get("value")));
                        deviceAttribute.setUnitName(String.valueOf(jsonParam.get("unitName")));
                        deviceAttribute.setDataType(String.valueOf(jsonParam.get("dataType")));
                        deviceAttributeService.save(deviceAttribute);
                    }
                }
            }
        }
        return "查询所有项目设备的属性快照 已完成！！！";
    }

    /**
     * 根据项目ID，批量查询属性的历史数据 -存入mongdb-deviceHistoryData表
     *
     * @author : juzipi123
     * @param username 用户名
     * @param password 密码
     * @param projId   项目id
     * @param start    开始时间（时间戳）
     * @param end      结束时间（时间戳）
     * @param metric   多个属性flag(可选,不填查询设备下所有参数)
     * @return 结果
     */
    @Override
    public String queryDeviceParamHistoryDataByProjId(String username, String password, Long projId, Long start, Long end, String metric) {
        //老狗登陆地址
        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        //查询出项目下的所有设备
        for (String deviceId : deviceService.selectByprojId(projId)) {
            //每个设备区查询 属性的历史数据
            String reqUrl = host + queryDeviceParamHistoryData + "?deviceId=" + deviceId + "&start=" + start + "&end=" + end;
            String s = client.QueryDeviceParamHistoryData(reqUrl, token);
            JSONObject resultJson = JSONUtil.parseObj(s);

            //存入mongdb的数据库
            DeviceHistoryDataMon deviceHistoryData = new DeviceHistoryDataMon();
            deviceHistoryData.setDeviceid(deviceId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String start2 = sdf.format(new Date(start * 1000));
            String end2 = sdf.format(new Date(end * 1000));
            deviceHistoryData.setStart(start2);
            deviceHistoryData.setEnd(end2);
            deviceHistoryData.setData(resultJson.get("data"));
//            mongoUtil.save(deviceHistoryData);
        }
        return null;
    }

    /**
     * 根据设备ID，查询属性的历史数据 -存入mongdb-deviceHistoryData表
     *
     * @author : juzipi123
     * @param username 用户名
     * @param password 密码
     * @param deviceId 设备id
     * @param start 开始时间（时间戳）
     * @param end 结束时间（时间戳）
     * @param metric 多个属性flag(可选,不填查询设备下所有参数)
     * @return
     */
    @Override
    public String queryDeviceParamHistoryDataBydeviceId(String username, String password, String deviceId, String start, String end, String metric) {
        //老狗登陆地址
        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        //每个设备区查询 属性的历史数据
        String reqUrl = host + queryDeviceParamHistoryData + "?deviceId=" + Long.parseLong(deviceId) + "&start=" + Long.parseLong(start) + "&end=" + Long.parseLong(end) + "&metric=" + metric;
        String s = client.QueryDeviceParamHistoryData(reqUrl, token);
        JSONObject resultJson = JSONUtil.parseObj(s);

        //存入mongdb的数据库
        DeviceHistoryDataMon deviceHistoryData = new DeviceHistoryDataMon();
        deviceHistoryData.setDeviceid(deviceId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start2 = sdf.format(new Date(Long.parseLong(start) * 1000));
        String end2 = sdf.format(new Date(Long.parseLong(end) * 1000));
        deviceHistoryData.setStart(start2);
        deviceHistoryData.setEnd(end2);
        deviceHistoryData.setData(resultJson.get("data"));
//        mongoUtil.save(deviceHistoryData);
        return String.valueOf(deviceHistoryData);
    }


    /**
     * 每个设备根据 昨天的23：00：00 去拉取数据并计算，加入到表‘plan_data’备用
     *
     * @author : juzipi123
     * @param projId 项目id
     * @param deviceId 设备id
     * @param start 开始时间
     * @param end 结束时间
     * @param metric 点位
     * @return 结果
     */
    @Override
    public String savePlanData( String projId, String deviceId, String start, String end, String metric) {
        log.info("传入方法savePlanData的参数 : {},{},{},{}",projId,deviceId,start,end,metric);
        DeviceHistoryDataMon deviceHistoryData = new DeviceHistoryDataMon();
        deviceHistoryData.setDeviceid(deviceId);
        Device device = deviceService.selectByDeviceId(deviceId);
        deviceHistoryData.setDeviceName(device.getName());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start2 = sdf.format(new Date(Long.parseLong(start) * 1000));
        String end2 = sdf.format(new Date(Long.parseLong(end) * 1000));
        deviceHistoryData.setStart(start2);
        deviceHistoryData.setEnd(end2);

        String token = tokenService.getLaoGouToken();
        log.info("获取老狗登陆token：{}",token);

        //查询 设备点位表
        DevicePoint devicePoint = devicePointService.getById(projId);
        String flagList = devicePoint.getFlag();
        //点位可以是多个
        String[] split = flagList.split(",");
        for (String flag : split) {
            //属性的历史数据
            String reqUrlStart =
                    host + queryDeviceParamHistoryData + "?deviceId=" + Long.parseLong(deviceId) + "&start=" + start + "&end=" + end + "&metric=" + flag;
            log.info("属性的历史数据 请求路径：{}", reqUrlStart);
            String resultStart = null;
            try {
                resultStart = client.QueryDeviceParamHistoryData(reqUrlStart, token);
                PandData pandData = new PandData();
                pandData.setFlag(flag);
                pandData.setProjId(projId);
                pandData.setDeviceId(deviceId);
                pandData.setData(JSONUtil.parseObj(resultStart));
//                mongoUtil.save(pandData);
            } catch (Exception e) {
                log.error("批量查询属性的历史数据 异常 异常地址：{},异常原因：{}", reqUrlStart, e);
                //存入mongdb的数据库
                deviceHistoryData.setData(reqUrlStart + e);
                deviceHistoryData.setDateTime(sdf.format(new Date()));
//                mongoUtil.save(deviceHistoryData);
                e.printStackTrace();
            }
            log.info("请求路径返回值：{}", resultStart);

            JSONObject resultStartJson = JSONUtil.parseObj(resultStart);

            log.info("resultStartJson", resultStartJson);

            JSONArray data = JSONUtil.parseArray(resultStartJson.get("data"));

            if (data.size() <= 0) {
                log.error("项目:{}， 设备：{}, 没有查询到有效数据", projId, deviceId);
                //存入mongdb的数据库

                deviceHistoryData.setData(projId+ "的点位 "+flag+ "：没有查询到有效数据");
                deviceHistoryData.setDateTime(sdf.format(new Date()));
//                mongoUtil.save(deviceHistoryData);
            } else {
                log.info("数组：{}", data);
                String startFlag1 = "";
                String startRealTime = "";
                String endFlag1 = "";
                String endRealTime = "";

                data.sort(Comparator.comparing(obj -> {
                    Long value = ((JSONObject) obj).getLong("datetime");
                    return value;
                }));

                JSONObject startDataJson = data.getJSONObject(0);
                log.info("startDataJson:{}", startDataJson);
                //datetime 时间戳
                startRealTime = String.valueOf(startDataJson.get("datetime"));
                //flag1 数据
                startFlag1 = String.valueOf(startDataJson.get(flag));

                JSONObject endDataJson = data.getJSONObject(data.size() - 1);
                log.info("endDataJson:{}", endDataJson);
                //datetime 时间戳
                endRealTime = String.valueOf(endDataJson.get("datetime"));
                //flag1 数据
                endFlag1 = String.valueOf(endDataJson.get(flag));

                PlanData planData = new PlanData();
                if (ObjectUtil.isEmpty(endFlag1) || ObjectUtil.isEmpty(startFlag1)) {
                    //存入mongdb的数据库
                    deviceHistoryData.setData(projId + "：开始时间或者结束时间，数据为空");
                    deviceHistoryData.setDateTime(sdf.format(new Date()));
//                    mongoUtil.save(deviceHistoryData);
                    log.info("{},的{}或者{}空了", deviceId, start, end);
                } else {

                    double v = Double.parseDouble(String.valueOf(endFlag1)) - Double.parseDouble(String.valueOf(startFlag1));
                    planData.setData(String.valueOf(v));

                    planData.setStart(startRealTime);
                    planData.setEnd(endRealTime);

                    //结束时间的 年-月-日 加上 00:00:00 不取实际
                    String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(endRealTime) * 1000L));
                    planData.setDateTime(format + " 00:00:00");

                    planData.setDeviceId(deviceId);

                    //根据projId 查出“enterprise”表中的 社会信用代码
                    Enterprise enterprise = enterpriseService.queryById(projId);
                    if (ObjectUtil.isEmpty(enterprise)) {
                        //存入mongdb的数据库
                        deviceHistoryData.setData(projId + "此项目在企业表中不存在");
                        deviceHistoryData.setDateTime(sdf.format(new Date()));
//                        mongoUtil.save(deviceHistoryData);
                        log.info("此项目在企业表中不存在");
                    }
                    planData.setEnterpriseCode(enterprise.getEnterpriseCode());

                    planData.setStartFlag1(startFlag1);
                    planData.setEndFlag1(endFlag1);
                    planData.setProjId(projId);
                    log.info("即将新增的数据：{}", planData);
                    planDataService.insert(planData);
                    log.info("返回值：{}", String.valueOf(planData));
                    return String.valueOf(planData);
                }
            }
        }
        return "处理结束!";
    }

    /**
     * 开始时间 属性的历史数据
     *
     * @author : juzipi123
     * @param deviceId 设备id
     * @param start 时间
     * @param token token
     * @param flag 点位
     * @return
     */
    @NotNull
    private JSONArray getDeviceParamHistoryData(String deviceId, Long start, String token, String flag) {
        String reqUrlStart =
                host + queryDeviceParamHistoryData + "?deviceId=" + Long.parseLong(deviceId) + "&start=" + start + "&end=" + (start + 600) + "&metric=" + flag;
        String resultStart = client.QueryDeviceParamHistoryData(reqUrlStart, token);
        log.info("resultStart:{}",resultStart);
        JSONObject resultStartJson = JSONUtil.parseObj(resultStart);

        log.info("resultStartJson", resultStartJson);

        return JSONUtil.parseArray(resultStartJson.get("data"));
    }

    /**
     * 批量新增数据 PlanData
     *
     * @author : juzipi123
     * @return 结果
     */
    @Override
    public Boolean savePlanDatas() {
        //取到昨天，前天23点整的，时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 50, 0);
        long today = calendar.getTime().getTime() / 1000;
        long yesterday = today - 86400;
        long beforeYesterday = yesterday - 86400;
        log.info("今天23点零分零秒:{} " + today);
        log.info("昨天23点零分零秒:{} " + yesterday);
        log.info("前天23点零分零秒:{} " + beforeYesterday);

        //取 设备点位表 里 需要上报的项目ID
        DevicePointVO devicePointVO = new DevicePointVO();

        //1：需要；0：不需要
        devicePointVO.setEscalation("1");
        List<DevicePoint> list = devicePointService.queryByDevicePointPaginVO(devicePointVO);
        if(ObjectUtil.isEmpty(list)){
            log.info("设备点位表 中没有需要上报的企业");
            return true;
        }
        for (DevicePoint devicePoint : list) {
            //根据项目Id 查询项目下所以设备的List
            String projectId = devicePoint.getProjectId();
            List<String> deviceIdList = deviceService.selectByprojId(Long.parseLong(projectId));
            if(!ObjectUtil.isEmpty(deviceIdList)){
                for (String deviceId : deviceIdList) {
                    //每个设备根据 昨天的23：50：00 去拉取数据并计算，加入到表‘plan_data’备用
                    savePlanData( projectId, deviceId, String.valueOf(beforeYesterday), String.valueOf(yesterday), null);
                }
            }else {
                log.info("项目：{}下，没有设备",projectId);
            }
        }
        return true;
    }


}
